<?php

/***************************************************************
 *  Copyright notice
 *
 *  (c) 2011 Gerhard Kollinger <gerhard@kollinger.it>
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 * Hint: use extdeveval to insert/update function index above.
 */

require_once(PATH_tslib.'class.tslib_pibase.php');

/**
 * Replacer function for deprecated mysql_escape_string()
 *
 * @param $unescaped_string
 * @return string
 */
function mysql_escape_string_replace($unescaped_string) {
    /** @noinspection PhpDeprecationInspection */
    return mysql_escape_string($unescaped_string);
}


/**
 * Plugin 'Listview of Artists/Guests' for the 'gk_eisview' extension.
 *
 * @author        Gerhard Kollinger <gerhard@kollinger.it>
 * @package       TYPO3
 * @subpackage    tx_gkeisview
 */
class tx_gkeisview_pi1 extends tslib_pibase {
    var $prefixId = 'tx_gkeisview_pi1'; // Same as class name
    var $scriptRelPath = 'pi1/class.tx_gkeisview_pi1.php'; // Path to this script relative to the extension dir.
    var $extKey = 'gk_eisview'; // The extension key.
    var $pi_checkCHash = TRUE;
    private $artist_name_array = array();
    private $artist_name_array_count = array();
    private $artist_list_pid_music;
    private $artist_list_pid_discourse;
    private $allowCaching = TRUE;
    const MYSQL_DEBUG = TRUE;
    const MY_IP       = '84.115.177.240';
    public $mysqli;
    public $artist_marker_array;
    public $tpl_artist;
    public $artist_list_pid;
    public $templateCode;
    public $tpl_search;


    private static function silentDebug($info = NULL, $mixedOutputVar = 'no_value', $dieAfter = NULL, $htmlCommented = TRUE) {
        if($_SERVER['REMOTE_ADDR'] == self::MY_IP) {
            if($mixedOutputVar != 'no_value') {
                $output = is_array($mixedOutputVar) ? print_r($mixedOutputVar, TRUE) : $mixedOutputVar;
                $output = is_string($output) ? $output : var_export($output, TRUE);
                if($htmlCommented) {
                    echo '<!--'.$info.': '.$output.'-->'."\n";
                } else {
                    echo $info.': '.$output.'<br />'."\n";
                }
                if($dieAfter) {
                    die();
                }
            }
        }

        return;
    }

    /**
     * The main method of the PlugIn
     *
     * @param    string        $content: The PlugIn content
     * @param    array         $conf   : The PlugIn configuration
     * @return    The content that is displayed on the website
     */
    function main($content, $conf) {
        $this->pi_initPIflexForm();
        $this->conf = $conf;
        $this->pi_setPiVarDefaults();
        $this->pi_loadLL();

        $this->connectDB();

        // Template Code
        $langKey             = $GLOBALS['TSFE']->sys_language_uid == 0 ? "DE" : "EN";
        $templateFile        = $this->getTemplateName($langKey);
        $this->templateCode  = $this->cObj->fileResource($templateFile);
        $artist_display_type = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'displaytype');

        $artist = $this->piVars["artist"] == "" ? $this->piVars["guest"] : $this->piVars["artist"];

        if(! empty($artist)) {
            $content = $this->getArtistDetail($artist);
        } elseif($artist_display_type == "search") {
            $content = $this->getSearchForm();
        } else {
            $content = $this->getArtistList();
        }

        return $this->pi_wrapInBaseClass($content);
    }

    function getSearchForm() {
        $this->tpl_search = $this->cObj->getSubpart($this->templateCode, '###ARTIST_SEARCH###');
        $main_subparts    = array();
        $tpl_search_form  = $this->cObj->getSubpart($this->tpl_search, '###ARTIST_SEARCH_FORM###');
        $search_marker    = array();
        $search_subparts  = array();
        $artist_category  = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'category');
        $artists_per_page = $this->piVars["artists_per_page"] ? $this->piVars["artists_per_page"] : 9;
        $artists_per_page = $this->piVars["guests_per_page"] ? $this->piVars["guests_per_page"] : $artists_per_page;
        $year             = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'year');

        $link                            = $this->pi_linkTP_keepPIvars_url(array(), FALSE, TRUE);
        $search_marker["###FORM_URL###"] = $link;

        $search_marker["###ACTUAL_PID###"] = $GLOBALS["TSFE"]->id;

        $search_marker["###PASSED_ARTIST_NAME###"] = $this->piVars["artist_name"] ? $this->piVars["artist_name"] : $this->piVars["guest_name"];
        for($i = 0; $i <= 100; $i ++) {
            $search_marker["###ARTISTS_PER_PAGE_".$i."_CHECKED###"] = "";
        }
        $search_marker["###ARTISTS_PER_PAGE_".$artists_per_page."_CHECKED###"] = "checked";

        $search_subparts["###CATEGORY_CHECKBOXES###"] = $this->getCategoryCheckboxes($artist_category, $year);
        $search_subparts["###LOCATION_CHECKBOXES###"] = $this->getLocationCheckboxes($artist_category, $year);
        $search_subparts["###DATE_CHECKBOXES###"]     = $this->getDateCheckboxes($artist_category, $year);

        $main_subparts["###ARTIST_SEARCH_FORM###"]    = $this->cObj->substituteMarkerArrayCached($tpl_search_form, $search_marker, $search_subparts);
        $main_subparts["###ARTIST_SEARCH_RESULTS###"] = $this->getSearchResults();

        return $this->cObj->substituteMarkerArrayCached($this->tpl_search, array(), $main_subparts);
    }

    function getSearchResults() {
        $tpl_search_results      = $this->cObj->getSubpart($this->tpl_search, '###ARTIST_SEARCH_RESULTS###');
        $search_results_subparts = array();
        $tpl_artist              = $this->cObj->getSubpart($tpl_search_results, '###ARTIST###');
        $tpl_pagebrowser         = $this->cObj->getSubpart($tpl_search_results, '###PAGEBROWSER###');
        $pagebrowser_marker      = array();
        $pagebrowser_subparts    = array();
        $artists_per_page        = $this->piVars["artists_per_page"] ? $this->piVars["artists_per_page"] : 9;
        $artists_per_page        = $this->piVars["guests_per_page"] ? $this->piVars["guests_per_page"] : $artists_per_page;
        $artist_category         = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'category') == "all" ? "" : $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'category');
        $get_events              = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'getevents');
        $year                    = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'year');
        $year_query              = $year == "all" || $year == "" ? "" : 'and view_artist.event_year = '.$year;

        if(! empty($this->piVars["page"]) && $this->piVars["page"] > 0) {
            $page = $this->piVars["page"];
        } else {
            $page = 1;
        }


        if($this->piVars) {
            $artist_name    = $this->piVars["artist_name"] ? mysql_escape_string_replace($this->piVars["artist_name"]) : mysql_escape_string_replace($this->piVars["guest_name"]);
            $category_array = $this->piVars["category"];
            $location_array = $this->piVars["location"];
            $date_array     = $this->piVars["date"];

            $artist_name_array = explode(" ", $artist_name);
            $artist_name_query = "(";
            foreach($artist_name_array as $artist_name_part) {
                $artist_name_query .= "view_event_appearance.artist_name like '%".$artist_name_part."%' and ";
            }
            $artist_name_query = substr($artist_name_query, 0, - 4);
            $artist_name_query .= ") and ";

            if(! empty($category_array)) {
                $category_query = "(";

                foreach($category_array as $category) {
                    $category_query .= "view_artist.cat_type2 like '%".mysql_escape_string_replace(preg_replace("#A-V#", "A/V", $category))."%' or ";
                }
                $category_query = substr($category_query, 0, - 4);

                $category_query .= ") and ";
            } else {
                $category_query = "view_artist.cat_type2 like '%' and ";
            }

            if(! empty($location_array)) {
                $location_query = "(";

                foreach($location_array as $location) {
                    $location_query .= "view_event_appearance.location_name like '%".mysql_escape_string_replace($location)."%' or ";
                }
                $location_query = substr($location_query, 0, - 4);

                $location_query .= ") and ";
            } else {
                $location_query = "view_event_appearance.location_name like '%' and ";
            }

            if(! empty($date_array)) {
                $date_query = "(";

                foreach($date_array as $date) {
                    $date_query .= "view_event_appearance.date_date like '%".mysql_escape_string_replace($date)."%' or ";
                }
                $date_query = substr($date_query, 0, - 4);

                $date_query .= ") ";
            } else {
                $date_query = "view_event_appearance.date_date like '%' ";
            }
            $query = "select distinct(view_event_appearance.artist_id)
			from view_event_appearance 
			join view_artist on view_event_appearance.artist_id = view_artist.artist_id 
			where ".$artist_name_query.$category_query.$location_query.$date_query."and view_event_appearance.cat_type like '%".$artist_category."%' ".$year_query." order by view_artist.artist_name asc";

            $all_artists_query = "select *
            from view_event_appearance 
            join view_artist on view_event_appearance.artist_id = view_artist.artist_id 
            where ".$artist_name_query.$category_query.$location_query.$date_query."and view_event_appearance.cat_type like '%".$artist_category."%' ".$year_query." group by view_artist.artist_name "." order by view_artist.priority_class asc, view_artist.priority asc, view_artist.artist_name asc";
        } else {
            $query = "select distinct(view_event_appearance.artist_id)
			from view_event_appearance 
			join view_artist on view_event_appearance.artist_id = view_artist.artist_id 
			where view_event_appearance.cat_type like '%".$artist_category."%' ".$year_query." order by view_artist.artist_name asc";

            $all_artists_query = "select *
            from view_event_appearance 
            join view_artist on view_event_appearance.artist_id = view_artist.artist_id 
            where view_event_appearance.cat_type like '%".$artist_category."%' ".$year_query." group by view_artist.artist_name "." order by view_artist.priority_class asc, view_artist.priority asc, view_artist.artist_name asc";
        }

        $fetched_artist_array = $this->getQueryResultArray($query);
        $artist_count         = count($fetched_artist_array);

        // All Artists Wrap
        $all_artists         = $this->getQueryResultArray($all_artists_query);
        $all_artists_tpl     = $this->cObj->getSubpart($tpl_search_results, '###ALL_ARTISTS###');
        $all_artists_content = '';

        foreach($all_artists as $artist_array) {
            $all_artists_markers  = $this->getArtistMarker($artist_array, "view_artist", 100);
            $all_artists_subparts = $this->getArtistSubparts($artist_array);

            $all_artists_content .= $this->mySubstituteMarkerArray($all_artists_tpl, $all_artists_markers, $all_artists_subparts);
        }
        // substr() to get rid of last artist seperator in template
        $search_results_subparts['###ALL_ARTISTS###'] = substr($all_artists_content, 0, strrpos($all_artists_content, '>') + 1);


        // Search Results
        $query        = $this->getArtistsQueryPerFetchedArtistArray($fetched_artist_array, $artists_per_page, $page);
        $result_array = $this->getQueryResultArray($query);

        $search_results_subparts["###ARTIST###"] = "";
        $this->artist_marker_array               = array();

        if(empty($result_array)) {
            $search_results_subparts["###NO_RESULT###"] = $this->cObj->getSubpart($tpl_search_results, '###NO_RESULT###');
            $pagebrowser                                = FALSE;
        } else {
            $search_results_subparts["###NO_RESULT###"] = "";
            $pagebrowser                                = TRUE;
        }

        foreach($result_array as $artist_array) {
            $artist_id = $artist_array["artist_id"];

            $this->artist_marker_array = $this->getArtistMarker($artist_array, "view_artist");
            $artist_subpart_array      = $this->getArtistSubparts($artist_array);

            // get artist event appearance
            if(! isset($get_events)) {
                $artist_subpart_array["###appearance###"] = $this->fillArtistAppearancesSubpart($artist_id, $tpl_artist);
            } else {
                if($get_events == 1) {
                    $artist_subpart_array["###appearance###"] = $this->fillArtistAppearancesSubpart($artist_id, $tpl_artist);
                }
            }

            $search_results_subparts["###ARTIST###"] .= $this->mySubstituteMarkerArray($tpl_artist, $this->artist_marker_array, $artist_subpart_array);
            //$search_results_subparts["###ARTIST###"] .= $this->cObj->substituteMarkerArrayCached($tpl_artist, $this->artist_marker_array, $artist_subpart_array);
        }


        // PageBrowser
        if($pagebrowser) {
            $actual_page             = $page;
            $page_count              = $artist_count < $artists_per_page ? 1 : ceil($artist_count / $artists_per_page);
            $prev_page               = $actual_page == 1 ? 1 : $actual_page - 1;
            $next_page               = $actual_page == $page_count ? $page_count : $actual_page + 1;
            $tpl_page_num_browser    = $this->cObj->getSubpart($tpl_pagebrowser, '###PAGE_NUM_BROWSER###');
            $page_num_browser_marker = array();
            $addurlParameters        = array();
            $z                       = 1;

            $addurlParameters['page']                = $prev_page;
            $link                                    = $this->pi_linkTP_keepPIvars_url($addurlParameters, FALSE, FALSE);
            $pagebrowser_marker["###PREV_NR_URL###"] = $link;

            $addurlParameters['page']                = $next_page;
            $link                                    = $this->pi_linkTP_keepPIvars_url($addurlParameters, FALSE, FALSE);
            $pagebrowser_marker["###NEXT_NR_URL###"] = $link;


            $pagebrowser_subparts["###PAGE_NUM_BROWSER###"] = "";
            for($i = 1; $i <= $page_count; $i ++) {
                $z ++;

                $addurlParameters['page']                      = $i;
                $link                                          = $this->pi_linkTP_keepPIvars_url($addurlParameters, FALSE, FALSE);
                $page_num_browser_marker["###PAGE_NUM_URL###"] = $link;

                $page_num_browser_marker["###PAGE_NUM###"] = $i;

                if($i == $actual_page) {
                    $page_num_browser_marker["###PAGE_NUM_ACT###"] = "active";
                } else {
                    $page_num_browser_marker["###PAGE_NUM_ACT###"] = "";
                }

                $pagebrowser_subparts["###PAGE_NUM_BROWSER###"] .= $this->mySubstituteMarkerArray($tpl_page_num_browser, $page_num_browser_marker, array());
            }

            if($z == 1) {
                $i = 1;

                $addurlParameters['page']                      = $i;
                $link                                          = $this->pi_linkTP_keepPIvars_url($addurlParameters, FALSE, FALSE);
                $page_num_browser_marker["###PAGE_NUM_URL###"] = $link;

                $page_num_browser_marker["###PAGE_NUM###"] = $i;

                if($i == $actual_page) {
                    $page_num_browser_marker["###PAGE_NUM_ACT###"] = "active";
                } else {
                    $page_num_browser_marker["###PAGE_NUM_ACT###"] = "";
                }

                $pagebrowser_subparts["###PAGE_NUM_BROWSER###"] .= $this->mySubstituteMarkerArray($tpl_page_num_browser, $page_num_browser_marker, array());
            }

            $search_results_subparts["###PAGEBROWSER###"] = $this->mySubstituteMarkerArray($tpl_pagebrowser, $pagebrowser_marker, $pagebrowser_subparts);
        } else {
            $search_results_subparts["###PAGEBROWSER###"] = "";
        }


        return $this->mySubstituteMarkerArray($tpl_search_results, array(), $search_results_subparts);
    }

    function getArtistsQueryPerFetchedArtistArray($fetched_artist_array, $artists_per_page, $page) {
        if(! $fetched_artist_array) {
            return FALSE;
        }

        $query = "select * from view_artist where ";

        foreach($fetched_artist_array as $artist) {
            $artist_id = $artist["artist_id"];

            $query .= "artist_id = '".$artist_id."' or ";
        }
        $query = substr($query, 0, - 4);
        $query .= " order by artist_name asc";
        $query .= " limit ".(($page - 1) * $artists_per_page).", ".$artists_per_page;

        return $query;
    }

    function mySubstituteMarkerArray($tpl, $marker, $subparts) {
        // http://dmitry-dulepov.com/article/why-substitutemarkerarraycached-is-bad.html#ixzz1WzRK0SKR
        $content = $this->cObj->substituteMarkerArray($tpl, $marker);
        foreach($subparts as $subPart => $subContent) {
            $content = $this->cObj->substituteSubpart($content, $subPart, $subContent);
        }

        return $content;
    }

    function getCategoryCheckboxes($artist_category, $year) {
        $tpl_checkbox        = $this->cObj->getSubpart($this->templateCode, '###CATEGORY_CHECKBOXES###');
        $marker              = array();
        $subparts            = array();
        $category_checkboxes = "";

        $artist_category     = $artist_category == "all" ? "" : $artist_category;
        $category_year_query = $year == "all" || $year == "" ? "" : 'and event_year = '.$year;

        $category_strings = $this->getQueryResultArray("
		SELECT distinct cat_type2 
		from view_artist_light 
		where cat_type2 != '' and 
		cat_type like '%".$artist_category."%' ".$category_year_query);

        $categories = array();

        foreach($category_strings as $category_string) {
            $category_array = explode(",", $category_string["cat_type2"]);

            foreach($category_array as $category) {
                array_push($categories, $category);
            }
        }
        $categories = array_unique($categories);

        foreach($categories as $category) {
            // weil realurl mit dem slash nicht klarkommen würde
            $category_renamed = preg_replace("#A/V#", "A-V", $category);

            $marker["###CATEGORY_VALUE###"] = $category_renamed;
            $marker["###CATEGORY_NAME###"]  = $this->getCorrectCategoryName($category);


            if(@array_search($category_renamed, $this->piVars["category"]) !== FALSE && ! empty($this->piVars["category"])) {
                $marker["###CATEGORY_CHECKED###"] = "checked";
                $marker["###CATEGORY_CHECKED###"] = "";
            } else {
            }

            $category_checkboxes .= $this->cObj->substituteMarkerArrayCached($tpl_checkbox, $marker, $subparts);
        }

        return $category_checkboxes;
    }

    function getCorrectCategoryName($category) {
        if($GLOBALS['TSFE']->sys_language_uid == 0) {
            $de_names = array("#discussion#", "#workshop#", "#video-stream#", "#lecture#", "#film#", "#A/V#", "#music#", "#Q+A#", "#visuals#", "#literature#", "#installation#", "#performance#");

            $en_names = array("Diskussion", "Workshop", "Video-Stream", "Vortrag", "Film", "A/V", "Musik", "Q&A", "Visuals", "Literatur", "Installation", "Performance");

            $category = preg_replace($de_names, $en_names, $category);
        }

        return $category;
    }

    function getLocationCheckboxes($artist_category, $year) {
        $tpl_checkbox        = $this->cObj->getSubpart($this->templateCode, '###LOCATION_CHECKBOXES###');
        $marker              = array();
        $subparts            = array();
        $location_checkboxes = "";

        $artist_category  = $artist_category == "all" ? "" : $artist_category;
        $event_year_query = $year == "all" || $year == "" ? "" : 'and event_year = '.$year;

        $locations = $this->getQueryResultArray("select distinct location_name
		from view_event_light 
		where location_name != '' and 
		cat_type like '%".$artist_category."%' ".$event_year_query." order by location_name asc");

        foreach($locations as $location) {
            $marker["###LOCATION_VALUE###"] = $location["location_name"];

            if(@array_search($location["location_name"], $this->piVars["location"]) !== FALSE && ! empty($this->piVars["location"])) {
                $marker["###LOCATION_CHECKED###"] = "checked";
            } else {
                $marker["###LOCATION_CHECKED###"] = "";
            }

            $location_checkboxes .= $this->cObj->substituteMarkerArrayCached($tpl_checkbox, $marker, $subparts);
        }

        return $location_checkboxes;
    }

    function getDateCheckboxes($artist_category, $year) {
        $tpl_checkbox    = $this->cObj->getSubpart($this->templateCode, '###DATE_CHECKBOXES###');
        $marker          = array();
        $subparts        = array();
        $date_checkboxes = "";

        $artist_category   = $artist_category == "all" ? "" : $artist_category;
        $artist_year_query = $year == "all" || $year == "" ? "" : 'and event_year = '.$year;

        $dates = $this->getQueryResultArray("select distinct date_date
											from view_event_light 
											where date_date != '' and 
											cat_type like '%".$artist_category."%' ".$artist_year_query." order by date_date asc");

        foreach($dates as $date) {
            $marker["###DATE_VALUE###"]    = $date["date_date"];
            $marker["###DATE_NAME###"]     = $GLOBALS['TSFE']->sys_language_uid == 0 ? $this->getFormattedDate($date["date_date"]) : $this->getFormattedDate($date["date_date"], TRUE, "en");
            $marker["###de_datum_kurz###"] = $this->getFormattedDate($date["date_date"]);
            $marker["###de_datum_lang###"] = $this->getFormattedDate($date["date_date"], FALSE);
            $marker["###en_datum_kurz###"] = $this->getFormattedDate($date["date_date"], TRUE, "en");
            $marker["###en_datum_lang###"] = $this->getFormattedDate($date["date_date"], FALSE, "en");


            if(@array_search($date["date_date"], $this->piVars["date"]) !== FALSE && ! empty($this->piVars["date"])) {
                $marker["###DATE_CHECKED###"] = "checked";
            } else {
                $marker["###DATE_CHECKED###"] = "";
            }

            $date_checkboxes .= $this->cObj->substituteMarkerArrayCached($tpl_checkbox, $marker, $subparts);
        }

        return $date_checkboxes;
    }

    function getArtistList() {
        $tpl_main         = $this->cObj->getSubpart($this->templateCode, '###ARTIST_VIEW###');
        $this->tpl_artist = $this->cObj->getSubpart($tpl_main, '###ARTIST###');
        $subparts         = array();

        $artist_category            = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'category');
        $artist_subcategory         = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'subcategory');
        $artist_event_day           = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'eventday');
        $artist_eventlocation_array = explode(",", $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'eventlocation'));
        $artist_sort                = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'sort');
        $artist_year                = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'year');
        $get_events                 = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'getevents');

        switch($artist_event_day) {
            case "all":
            case "":
                $artist_event_day_query = " and (view_event_appearance.date_name LIKE '%' or view_event_appearance.date_date = null or view_event_appearance.date_date = '')";
                break;
            case "all_this_year":
                $artist_event_day_query = " and view_event_appearance.date_name LIKE '%".date("Y")."%'";
                break;
            default:
                $artist_event_day_query = " and view_event_appearance.date_name = '".$artist_event_day."'";
        }

        switch($artist_subcategory) {
            case "all":
            case "":
                $artist_subcategory_query = "";
                break;
            default:
                $artist_subcategory_query = "and view_artist.cat_type2 LIKE '%".$artist_subcategory."%'";
        }

        switch($artist_year) {
            case "all":
            case "":
                $artist_year_query = "and (view_event_appearance.event_year LIKE '%' or view_event_appearance.event_year = null or view_event_appearance.event_year = '') ";
                break;
            default:
                $artist_year_query = "and view_event_appearance.event_year = '".$artist_year."' ";
        }

        if(array_search("all", $artist_eventlocation_array) !== FALSE || array_search("", $artist_eventlocation_array) !== FALSE) {
            $artist_eventlocation_query = "and (view_event_appearance.location_name LIKE '%' or view_event_appearance.location_name = null or view_event_appearance.location_name = '') ";
        } else {
            $artist_eventlocation_query = "and (";
            foreach($artist_eventlocation_array as $artist_eventlocation) {
                $artist_eventlocation_query .= "view_event_appearance.location_name = '".$artist_eventlocation."' or ";
            }
            $artist_eventlocation_query = substr($artist_eventlocation_query, 0, - 4);
            $artist_eventlocation_query .= ") ";
        }
        $artist_query = "";

        switch($artist_category) {
            case "all":
            case "":
                $artist_category_query = "(view_artist.cat_type LIKE '%' OR view_artist.cat_type = null) ";
                break;
            default:
                $artist_category_query = "view_artist.cat_type = '".$artist_category."'";
        }

        $query = "
		select * from view_event_appearance 
		join view_artist on view_event_appearance.artist_id = view_artist.artist_id 
		where ".$artist_category_query.$artist_subcategory_query." ".$artist_query.$artist_event_day_query.$artist_eventlocation_query.$artist_year_query." order by ".$artist_sort;

        $result_array = $this->getQueryResultArray($query);

        $subparts["###ARTIST###"] = "";
        foreach($result_array as $artist_array) {
            $artist_name = $artist_array["artist_name"];
            $artist_id   = $artist_array["artist_id"];

            if($this->artistMultiple($artist_name)) {
                continue;
            }
            array_push($this->artist_name_array, $artist_name);

            $this->artist_marker_array = $this->getArtistMarker($artist_array, "view_artist, view_event_appearance");
            $artist_subpart_array      = $this->getArtistSubparts($artist_array);

            // get artist event appearance
            if(! isset($get_events)) {
                $artist_subpart_array["###appearance###"] = $this->fillArtistAppearancesSubpart($artist_id);
            } else {
                if($get_events == 1) {
                    $artist_subpart_array["###appearance###"] = $this->fillArtistAppearancesSubpart($artist_id);
                }
            }

            $subparts["###ARTIST###"] .= $this->cObj->substituteMarkerArrayCached($this->tpl_artist, $this->artist_marker_array, $artist_subpart_array);
        }

        return $this->cObj->substituteMarkerArrayCached($tpl_main, array(), $subparts);
    }

    function getArtistDetail($id) {
        $tpl_main         = $this->cObj->getSubpart($this->templateCode, '###ARTIST_VIEW###');
        $this->tpl_artist = $this->cObj->getSubpart($tpl_main, '###ARTIST###');
        $subparts         = array();

        // get the year subdomain from url to fetch correct artist if an artist was on elevate more than once (because artists will then appear multiple in db) url will be something like this: 2012.elevate.at/metallica
        // but this can be overruled by GET parameter "year"
        if( ! isset($this->piVars["artist_year"])) {
            list($artist_year) = $this->piVars["artist_year"];
        }else {
            $artist_year = explode(".", $_SERVER["HTTP_HOST"]);
        }
        $artist_year_query = is_numeric($artist_year) ? "and event_year = ".$artist_year : "";

        $query        = "select * from view_artist where url_shortcode = '".$id."' ".$artist_year_query." or artist_id = '".$id."' ".$artist_year_query." limit 1";
        $result_array = $this->getQueryResultArray($query);

        // add artist links to $result_array (we could loop artist links in special subpart, but this handling is as it was expected at the beginning)
        $different_link_types = $this->getQueryResultArray('select DISTINCT(link_type_code) from view_artist_detail_links');
        foreach($different_link_types as $link_type) {
            // first set all possible link types to provide empty subpart handling in FE
            for($i = 1; $i <= 5; $i++) {
                if($i == 1) {
                    $result_array[0]['link_'.$link_type['link_type_code']]          = '';
                    $result_array[0]['link_'.$link_type['link_type_code'].'_descr'] = '';

                    // unset these old links from db
                    /*
                    unset($result_array[0]['link_'.$link_type['link_type_code'].'_'.$i]);
                    unset($result_array[0]['link_'.$link_type['link_type_code'].'_'.$i.'_descr']);
                    unset($result_array[0]['link_'.$link_type['link_type_code'].$i]);
                    unset($result_array[0]['link_'.$link_type['link_type_code'].$i.'_descr']);
                    */
                } else {
                    $result_array[0]['link_'.$link_type['link_type_code'].'_'.$i]          = '';
                    $result_array[0]['link_'.$link_type['link_type_code'].'_'.$i.'_descr'] = '';

                    // unset these old links from db
                    /*
                    unset($result_array[0]['link_'.$link_type['link_type_code'].$i]);
                    unset($result_array[0]['link_'.$link_type['link_type_code'].$i.'_descr']);
                    */
                }

            }
        }

        // now add existing link types      
        $query        = "select * from view_artist_detail_links where artist_id = '".$result_array[0]['artist_id']."' order by link_priority ASC";
        $artist_links = $this->getQueryResultArray($query);
        $link_amount = array();

        foreach($artist_links as $artist_link) {
            if( ! $link_amount[$artist_link['link_type_code']]) {
                $result_array[0]['link_'.$artist_link['link_type_code']]          = $artist_link['link_url'];
                $result_array[0]['link_'.$artist_link['link_type_code'].'_descr'] = $artist_link['link_description'];
                $link_amount[$artist_link['link_type_code']] = 1;
            } else {
                $link_amount[$artist_link['link_type_code']]++;
                $result_array[0]['link_'.$artist_link['link_type_code']."_".$link_amount[$artist_link['link_type_code']]]          = $artist_link['link_url'];
                $result_array[0]['link_'.$artist_link['link_type_code']."_".$link_amount[$artist_link['link_type_code']].'_descr'] = $artist_link['link_description'];
            }
        }

        // parse results for template
        $subparts["###ARTIST###"] = "";
        foreach($result_array as $artist_array) {
            $this->artist_marker_array = $this->getArtistMarker($artist_array, "view_artist");
            $artist_subpart_array      = $this->getArtistSubparts($artist_array);

            // get artist event appearance
            $artist_subpart_array["###appearance###"] = $this->fillArtistAppearancesSubpart($artist_array["artist_id"]);

            $subparts["###ARTIST###"] .= $this->cObj->substituteMarkerArrayCached($this->tpl_artist, $this->artist_marker_array, $artist_subpart_array);
        }

        return $this->cObj->substituteMarkerArrayCached($tpl_main, array(), $subparts);
    }

    private function artistMultiple($artist_name, $count = FALSE) {
        if($count === TRUE) {
            $name_array = $this->artist_name_array_count;
        } else {
            $name_array = $this->artist_name_array;
        }

        if(array_search($artist_name, $name_array) === FALSE) {
            return FALSE;
        }

        return TRUE;
    }

    private function fillArtistAppearancesSubpart($artist_id, $template = TRUE) {
        if($template === TRUE) {
            $template = $this->tpl_artist;
        }

        $query        = "select * from view_event_appearance where artist_id = '".$artist_id."' order by date_date asc, time_begin asc";
        $result_array = $this->getQueryResultArray($query);

        $appearance_content = "";
        foreach($result_array as $appearance_array) {
            $appearance_marker_array  = $this->getArtistMarker($appearance_array, "view_event_appearance");
            $appearance_subpart_array = $this->getArtistSubparts($appearance_array);

            $tpl_appearance = $this->cObj->getSubpart($template, "###appearance###");
            $appearance_content .= $this->cObj->substituteMarkerArrayCached($tpl_appearance, $appearance_marker_array, $appearance_subpart_array);
        }

        return $appearance_content;
    }

    private function getQueryResultArray($query) {
        self::silentDebug($query);
        if(! $query) {
            return FALSE;
        }

        $results = $this->mysqli->query($query);

        if($this->mysqli->error != "" && self::MYSQL_DEBUG) {
            die("Mysql Error: ".$this->mysqli->error."<br><br>"."Betroffener Query: ".$query);
        }

        $result_array = array();
        while($result = $results->fetch_assoc()) {
            array_push($result_array, $result);
        }
        $results->close();

        return $result_array;
    }

    function getArtistMarker($artist_array, $table = "", $specific_zero_value = FALSE) {
        $artist_marker_array                = array();
        $artist_marker_array["###table###"] = $table;
        $year                               = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'year');

        $artist_array["bio_de"] = empty($artist_array["bio_long_de"]) ? $artist_array["bio_short_de"] : $artist_array["bio_long_de"];
        $artist_array["bio_en"] = empty($artist_array["bio_long_en"]) ? $artist_array["bio_short_en"] : $artist_array["bio_long_en"];

        foreach($artist_array as $key => $value) {
            if(empty($value) && $value != "0" || $value == "<br>") {
                $value = $specific_zero_value === FALSE ? $this->conf["artist-detail_zero-value"] : $specific_zero_value;

                if($key == "title_en") {
                    $value = $input_array["title"];
                } elseif($key == "sub_title_en") {
                    $value = $input_array["sub_title"];
                }
            }

            $artist_marker_array["###view_event_appearance_".$key."###"] = $value;


            if($key == "typoid") {
                $artist_marker_array["###event_url###"] = $this->pi_getPageLink($value);
            }

            if($key == "date_date") {
                $artist_marker_array["###de_datum_kurz###"] = $this->getFormattedDate($value);
                $artist_marker_array["###de_datum_lang###"] = $this->getFormattedDate($value, FALSE);
                $artist_marker_array["###en_datum_kurz###"] = $this->getFormattedDate($value, TRUE, "en");
                $artist_marker_array["###en_datum_lang###"] = $this->getFormattedDate($value, FALSE, "en");
            }

            // extract youtube video id
            if(preg_match("#video#", $key)) {
                if(preg_match("#v=([^&]+)#", $value, $player_id_matches)) {
                    if(isset($player_id_matches[1])) {
                        $artist_marker_array["###view_event_appearance_".$key."_player_id###"] = $player_id_matches[1];
                    }
                } elseif(preg_match("#vimeo#", $value)) {
                    $slashExplodedVimeoLink = explode('/', $value);
                    $artist_marker_array["###view_event_appearance_".$key."_player_id###"] = $slashExplodedVimeoLink[count($slashExplodedVimeoLink) - 1];
                    $artist_marker_array["###view_event_appearance_vimeo_id_1###"]         = $artist_marker_array["###view_event_appearance_".$key."_player_id###"]; //overite existing one used marker
                }
            }
        }

        $artist_list_pid = $artist_array["cat_type"] == "art" ? $this->artist_list_pid_music : $this->artist_list_pid_discourse;

        $addurlParameters = array();
        if($artist_array["artist_cat_type"] == "discourse") {
            $addurlParameters['guest'] = $artist_array["url_shortcode"];
        } else {
            if(isset($artist_array["artist_cat_type"])) {
                $addurlParameters['artist'] = $artist_array["url_shortcode"];
            } else {
                if($artist_array["cat_type"] == "discourse") {
                    $addurlParameters['guest'] = $artist_array["url_shortcode"];
                } else {
                    $addurlParameters['artist'] = $artist_array["url_shortcode"];
                }
            }
        }

        if($year && $year != "all") {
            $addurlParameters['artist_year'] = $year;
        }

        $link                                      = $this->pi_linkTP_keepPIvars_url($addurlParameters, $this->allowCaching, TRUE, $artist_list_pid);
        $artist_marker_array["###artist_url###"]   = $link;
        $link                                      = $this->pi_linkTP_keepPIvars_url(array(), TRUE, TRUE, $this->artist_list_pid);
        $artist_marker_array["###overview_url###"] = $link;

        $artist_marker_array["###markers###"] = print_r($artist_marker_array, TRUE);

        return $artist_marker_array;
    }

    function getArtistSubparts($artist_array) {
        $artist_subpart_array = array();

        foreach($artist_array as $key => $value) {
            if(empty($value) && $value != "0" || $value == "<br>") {
                $artist_subpart_array["###view_event_appearance_".$key."_subpart###"] = "";
            } else {
                $tpl_artist_subpart                                                    = $this->cObj->getSubpart($this->tpl_artist, "###view_event_appearance_".$key."_subpart###");
                $artist_subpart_array["###view_event_appearance_".$key."_subpart####"] = $this->cObj->substituteMarkerArrayCached($tpl_artist_subpart, $this->artist_marker_array, array());
            }
        }

        return $artist_subpart_array;
    }

    function getFormattedDate($date_date_from_db, $short = TRUE, $lang = "de") {
        $date_array = explode("-", $date_date_from_db);

        if(count($date_array) == 3) {
            $timestamp = mktime(0, 0, 0, $date_array[1], $date_array[2], $date_array[0]);
        } else {
            return;
        }

        /*
               if($lang == "de")
               {
                   setlocale(LC_TIME, "de_DE");

                   if($short)
                   {
                       $format = "%a. %d %b";
                   }
                   else
                   {
                       $format = "%A, %d %b";
                   }
               }
               else
               {
                   setlocale(LC_TIME, "en_US");
               }

               return strftime($format, $timestamp);
        */

        if($short) {
            $format = "D. d M";
        } else {
            $format = "l, d M";
        }

        $date = date($format, $timestamp);

        if($lang == "de") {
            $de_names = array("Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag", "Mo", "Di", "Mi", "Do", "Fr", "Sa", "So", "Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez", "Montag",);

            $en_names = array("#Monday#", "#Tuesday#", "#Wednesday#", "#Thursday#", "#Friday#", "#Saturday#", "#Sunday#", "#Mon#", "#Tue#", "#Wed#", "#Thu#", "#Fri#", "#Sat#", "#Sun#", "#Jan#", "#Feb#", "#Mar#", "#Apr#", "#May#", "#Jun#", "#Jul#", "#Aug#", "#Sep#", "#Oct#", "#Nov#", "#Dec#", "#Motag#",);

            $date = preg_replace($en_names, $de_names, $date);
        }

        return $date;
    }

    function connectDB() {
        $db_params = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['gk_eisview']);

        if(empty($db_params["artist_list_pid_music"]) || empty($db_params["artist_list_pid_discourse"])) {
            die("Bitte Artist-Liste-Musik PID und Artist-Liste-Diskurs PID im Extension Manager eintragen!");
        }
        $this->artist_list_pid_music     = $db_params["artist_list_pid_music"];
        $this->artist_list_pid_discourse = $db_params["artist_list_pid_discourse"];

        $this->mysqli = new mysqli('localhost', $db_params["user"], $db_params["pass"], $db_params["database"]);
        $this->mysqli->query("SET NAMES 'utf8'");

        /*
           * Use this instead of $connect_error if you need to ensure
           * compatibility with PHP versions prior to 5.2.9 and 5.3.0.
           */
        if(mysqli_connect_error() && self::MYSQL_DEBUG) {
            die('Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error());
        }
    }

    /**
     * Get multilanguage template
     *
     * @param    integer        $language: Language
     * @return    string        $t_name: Template
     **/
    function getTemplateName($language) {
        $artist_display_type = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'displaytype');
        $artist              = $this->piVars["artist"] == "" ? $this->piVars["guest"] : $this->piVars["artist"];

        if(! empty($artist)) {
            $artist_type_array = $this->getQueryResultArray("select cat_type from view_artist_light where url_shortcode = '".mysql_escape_string_replace($artist)."' or artist_id = '".mysql_escape_string_replace($artist)."'");

            if(isset($artist_type_array[0]["cat_type"]) && preg_match("#discourse#", $artist_type_array[0]["cat_type"])) {
                $t_type = "detail-discourse";
            } else {
                $t_type = "detail";
            }
        } else if($artist_display_type == "list") {
            $artist_category = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'category');

            if($artist_category == "discourse") {
                $t_type = "list-discourse";
            } else {
                $t_type = "list";
            }
        } else {
            $artist_category = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'category');

            if($artist_category == "discourse") {
                $t_type = "search-discourse";
            } else {
                $t_type = "search";
            }
        }

        $t_name            = $this->conf["template_folder_artist-list"].$language.$this->conf["template_name_artist-".$t_type];
        $standard_template = $this->conf["template_folder_artist-list"]."DE".$this->conf["template_name_artist-".$t_type];

        if(file_exists($t_name))
            return ($t_name); else if(file_exists($standard_template))
            return ($standard_template); else die ("<p align=center>"."Template: <b>".$t_name."</b> nicht gefunden!</p>");
    }

    function __destruct() {
        $this->mysqli->close();
    }
}


if(defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/gk_eisview/pi1/class.tx_gkeisview_pi1.php']) {
    include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/gk_eisview/pi1/class.tx_gkeisview_pi1.php']);
}

?>
